package br.ufc.si.filter;

import java.io.IOException;

import javax.persistence.EntityManager;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;

import br.ufc.database.util.JPAUtil;

@WebFilter("/*")
public class OpenEntityFilter implements Filter {

    public OpenEntityFilter() {
        // TODO Auto-generated constructor stub
    }

	public void destroy() {
		// TODO Auto-generated method stub
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		String uri = ((HttpServletRequest) request).getRequestURI();
		/**
		 * Verificação se a página requisitada é um JavaScript,imagem os css,
		 *  se for não é feita a abertura de EntityManager
		 */
		if (uri.contains("javax.faces.resource") || uri.matches(".+\\.(jpg|gif|JPG|GIF|png|PNG|css|js)")) {
			chain.doFilter(request, response);
		} else {
			System.err.println(uri);
			System.out.println("Abrindo Conexão");
			try {
				EntityManager em = JPAUtil.openEntityManager();
				JPAUtil.beginTransaction();
				chain.doFilter(request, response);
				if(em.getTransaction().isActive()){
					JPAUtil.commit();					
				}
			} catch (Throwable e) {
				JPAUtil.rollback();
				e.printStackTrace();
			} finally {
				JPAUtil.close();
				System.out.println("Fechando Conexão");
			}
		}

		
	}

	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}
	
}
